import { createVNode,defineComponent,onMounted,reactive,render,onBeforeUnmount } from "vue"


const DropdownComponent = defineComponent({
    props:{
        option:{type:Object},
    },
    setup(props,ctx){
        const state=reactive({
            option:props.option,
            isShow:false,
            top:0,
            left:0,
        })
        ctx.expose({
            showDropdown(option){
                state.option=option
                state.isShow=true
                let {top,left,height}=option.el.getBoundingClientRect()
                state.top=top+height
                state.left=left
            }
        });
        const classes=computed(()=>{
            'dropdown',
            {
                'dropdown-isShow':state.isShow
            }
        })
        const styles=computed(()=>({
            top:state.top+'px',
            left:state.left+'px'
        }))
        const el=ref(null)
        const onMousedownDocument=(e)=>{
            if(!el.value.contains(e.target)){
                state.isShow=false
            }
        }
        onMounted(()=>{
            //事件的传递行为是先铺获 在冒泡
            //之前为了阻止事件传播 我们给block 都增加了stopPropagation
            document.addEventListener('mousedown',onMousedownDocument,true)
        })
        onBeforeUnmount(()=>{
            document.removeEventListener('mousedown',onMousedownDocument)
        })
        return()=>{
            return <div class={classes.value} style={styles.value} ref={el}>
                下拉菜单内容区区域
            </div>
        }
    }
})



let vm
export function $dropdown(option){
    //element-plus中有el-dialog组件
    if(!vm){    
        let el=document.createElement('div')
        vm=createVNode(DropdownComponent,{option}) //将组件渲染成虚拟节点

        document.body.appendChild((render(vm,el),el)) //将虚拟节点渲染到el元素上
    }

    //将组件渲染到这个el元素上
    let {showDropdown}=vm.component.exposed
    showDropdown(option) //其他说民组件已经有了
}